﻿using System;
using System.Diagnostics;
using Smarly.Idml.RelaxNg.Generator.Model;
using Tenuto.Grammar;

namespace Smarly.Idml.RelaxNg.Generator.Proxy
{
	public class ReferenceExpBuilder : Builder<ReferenceExp>
	{
		[DebuggerStepThrough]
		protected internal ReferenceExpBuilder(ReferenceExp exp, Action<IObjectName> updateName) : base(exp, updateName) { }

		public override IStruct CreateIStruct()
		{
			Expression expression = Exp.exp;

			if (expression != null)
				return Factory(expression, UpdateName).CreateIStruct();

			return null;
		}

		public override IStruct Fill(IStruct getStruct = null)
		{
			getStruct = base.Fill(getStruct);

			if (getStruct == null)
				return null;

			if (getStruct is AttrStruct)
			{
				((AttrStruct)getStruct).Type = Exp.name;
			}
			else if (getStruct is EnumStruct)
			{
				var enumStr = (EnumStruct)getStruct;
				enumStr.IsNull = Exp.IsNullable;
				enumStr.Name = Exp.name;
			}
			else if (getStruct is ObjectStruct)
			{
				var obj = (ObjectStruct)getStruct;
				obj.Name = Exp.name;
			}
			else if (getStruct is ListStruct)
			{
				var obj = (ListStruct) getStruct;
				obj.Name = Exp.name;
			}
			else
			{
				throw new NotImplementedException();
			}

			return getStruct;
		}
	}
}